import secrets

from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.db import models

from ztds.settings import AUTH_USER_MODEL

class CustomUserManager(BaseUserManager):
    def create_user(self, account, password=None, **extra_fields):
        if not account:
            raise ValueError("账号必须填写")
        user = self.model(account=account, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, account, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        return self.create_user(account, password, **extra_fields)

class CustomUser(AbstractBaseUser):
    GENDER_CHOICES = [
        (1, '男'),
        (2, '女'),
        (3, '其他')
    ]

    account = models.CharField(max_length=255, verbose_name='账号',unique=True)
    password = models.CharField(max_length=255, verbose_name='密码')
    user_name = models.CharField(max_length=255, verbose_name='姓名')
    is_enabled = models.BooleanField(default=True, verbose_name='启用状态')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    quota = models.IntegerField(default=0, verbose_name='配额')
    major_class = models.CharField(max_length=255, null=True, blank=True, verbose_name='专业班级')
    gender = models.IntegerField(choices=GENDER_CHOICES, default=3, verbose_name='性别')
    interview_count = models.IntegerField(default=0, verbose_name='面试次数')
    USERNAME_FIELD = 'account'
    objects = CustomUserManager()
    class Meta:
        db_table = 'customUser'  # 指定数据库表名
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.account


# models.py
class UserToken(models.Model):
    user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE)
    key = models.CharField(max_length=64, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    expires_at = models.DateTimeField(null=True, blank=True)

    @classmethod
    def generate_token(cls, user):
        token = secrets.token_urlsafe(48)  # 生成高强度的随机Token‌:ml-citation{ref="4,7" data="citationList"}
        created = cls.objects.update_or_create(
            user=user,
            # expires_at=datetime.now() + timedelta(days=7)
            defaults={"key": token}
        )
        return token
    @classmethod
    def logout_by_token(cls, token_value):
        # 根据 Token 值删除记录
        deleted_count, _ = cls.objects.filter(key=token_value).delete()
        return deleted_count > 0
from django.utils import timezone



